// pages/detail/detail.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'

import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    list: {},
    isFollowed: false,
    isCollected: false,
    likeCount: 0,
    isLike: false,
    show: false, // 显示评论弹出层
    value: '',
    commentList: [],
    offset: '',
    isReachBottom: false, // 是否触发过上拉触底事件
    commentCount: 0, // 评论数
    totalPage: 0, // 上拉触底发请求的次数
    currentPage: 0
  },

  // 点击发布
  async issue() {
    // toast 提示
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/comments',
      method: 'POST',
      data: {
        target: this.data.id,
        art_id: this.data.list.art_id,
        content: this.data.value
      },
      header: {
        Authorization: `Bearer ${store.token}`
      },
    })
    console.log(res.data.data);
    this.setData({
      commentList: [res.data.data.new_obj, ...this.data.commentList]
    })
    this.setData({
      show: false,
      value: ''
    })
    Toast.success('评论成功');
  },

  // 显示评论弹窗
  commentClick() {
    this.setData({
      show: true
    })
  },

  // 关闭弹出层
  onClose() {
    this.setData({
      show: false
    })
  },

  // 文章点赞
  async like() {
    // toast 提示
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    console.log(this.data.isLikedArticle.includes(this.data.id));
    if (!this.data.isLikedArticle.includes(this.data.id.toString())) {
      const res = await wx.p.request({
        url: 'https://toutiao.itheima.net/v1_0/article/likings',
        method: 'POST',
        header: {
          Authorization: `Bearer ${store.token}`
        },
        data: {
          target: this.data.id.toString()
        }
      })
      this.setData({
        likeCount: this.data.likeCount + 1,
        isLike: true
      })
      console.log(this.data.id);
      this.updateArticleLiked(this.data.id.toString())
    } else {
      const res = await wx.p.request({
        url: `https://toutiao.itheima.net/v1_0/article/likings/${this.data.id}`,
        method: 'DELETE',
        header: {
          Authorization: `Bearer ${store.token}`
        }
      })
      this.setData({
        likeCount: this.data.likeCount - 1,
        isLike: false
      })
      console.log(this.data.id);
      this.updateArticleLiked(this.data.id.toString())
    }
    Toast.success('操作成功');
  },

  // 点击收藏
  async collect() {
    // toast 提示
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    if (!this.data.isCollected) {
      const res = await wx.p.request({
        url: 'https://toutiao.itheima.net/v1_0/article/collections',
        method: 'POST',
        header: {
          Authorization: `Bearer ${store.token}`
        },
        data: {
          target: this.data.id
        }
      })
      this.setData({
        isCollected: true
      })
    } else {
      const res = await wx.p.request({
        url: `https://toutiao.itheima.net/v1_0/article/collections/${this.data.id}`,
        method: 'DELETE',
        header: {
          Authorization: `Bearer ${store.token}`
        }
      })
      this.setData({
        isCollected: false
      })
    }
    Toast.success('操作成功');
  },

  // 点击关注
  async follow() {
    if (!this.data.isFollowed) {
      // 关注
      const res = await wx.p.request({
        url: 'https://toutiao.itheima.net/v1_0/user/followings',
        method: 'POST',
        header: {
          Authorization: `Bearer ${store.token}`
        },
        data: {
          target: this.data.list.aut_id
        }
      })
      this.setData({
        isFollowed: true
      })
    } else {
      // 取消关注
      await wx.p.request({
        url: `https://toutiao.itheima.net/v1_0/user/followings/${this.data.list.aut_id}`,
        method: 'DELETE',
        header: {
          Authorization: `Bearer ${store.token}`
        }
      })
      this.setData({
        isFollowed: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['refresh_token', 'token', 'info', 'isLikedArticle'],
      actions: ['updateRefreshToken', 'updateToken', 'updateInfo', 'updateArticleLiked']
    })
    console.log(options.id);
    this.setData({ id: options.id })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.getList()
    this.setData({
      isReachBottom: false
    })
  },

  async getList() {
    // 获取文章详情
    const res = await wx.p.request({
      url: `https://toutiao.itheima.net/v1_0/articles/${this.data.id}`,
      method: 'GET',
      header: {
        Authorization: `Bearer ${store.token}`
      },
    })

    // 处理 rich-text
    res.data.data.content = /\<ul/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<ul/gi, '<ul class="ul"') : res.data.data.content
    res.data.data.content = /\<li/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<li/gi, '<li class="li"') : res.data.data.content
    res.data.data.content = /\<p/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<p/gi, '<p class="p"') : res.data.data.content
    res.data.data.content = /\<h1/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<h1/gi, '<h1 class="h1"') : res.data.data.content
    res.data.data.content = /\<h2/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<h2/gi, '<h2 class="h2"') : res.data.data.content
    res.data.data.content = /\<blockquote/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<blockquote/gi, '<blockquote class="blockquote"') : res.data.data.content
    res.data.data.content =  /\<img/gi.test(res.data.data.content) ? res.data.data.content.replace(/\<img/gi, '<img class="img"') : res.data.data.content
    this.setData({ list: res.data.data })
    this.setData({ isFollowed: res.data.data.is_followed })
    this.setData({ isCollected: res.data.data.is_collected })
    this.setData({ likeCount: res.data.data.like_count })
    this.setData({ id: res.data.data.art_id })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  async onReachBottom() {
    // 第一次
    if(this.data.currentPage === 0) {
      const res = await wx.p.request({
        url: 'https://toutiao.itheima.net/v1_0/comments',
        method: 'GET',
        data: {
          type: 'a',
          source: this.data.id,
          limit: 10
        },
        header: {
          Authorization: `Bearer ${store.token}`
        }
      })
      this.setData({
        commentList: res.data.data.results, // 评价列表
        commentCount: res.data.data.total_count, // 评价总数
        offset: res.data.data.last_id,
        totalPage: Math.ceil(res.data.data.total_count / 10) + 1, // 总页数
        currentPage: this.data.currentPage + 1
      })
    } else {
      // 接下来的几次
      if (this.data.currentPage === this.data.totalPage) return
      this.getCommentList()
    }
  },

  async getCommentList() {
    const res = await wx.p.request({
      url: 'https://toutiao.itheima.net/v1_0/comments',
      method: 'GET',
      data: {
        type: 'a',
        source: this.data.id,
        limit: 10,
        offset: this.data.offset
      },
      header: {
        Authorization: `Bearer ${store.token}`
      }
    })
    this.setData({
      commentList: [...this.data.commentList, ...res.data.data.results],
      offset: res.data.data.last_id,
      currentPage: this.data.currentPage + 1
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})